<template>
  <div class="address-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="我的收货地址"
      left-arrow
      @click-left="onNavBack"
      right-text="新增地址"
      @click-right="onAddAddress"
    />

    <!-- 地址列表 -->
    <van-cell-group class="address-list" inset>
      <!-- 空状态 -->
      <div v-if="addressList.length === 0" class="empty-address">
        <van-empty description="暂无收货地址" />
      </div>
      
      <van-cell
        v-for="(address, index) in addressList"
        :key="address.id"
        :border="false"
        class="address-item"
      >
        <!-- 默认地址标记 -->
        <template #icon>
          <div class="default-tag" v-if="address.isDefault === 1">
            默
          </div>
        </template>

        <!-- 地址内容 -->
        <template #title>
          <div class="name-phone">
            {{ address.receiverName }} {{ address.receiverPhone }}
          </div>
          <div class="address-detail">
            {{ address.region }} {{ address.detailAddress }}
          </div>
        </template>

        <!-- 操作按钮组 -->
        <template #right-icon>
          <div class="address-actions">
            <!-- 设为默认按钮 - 非默认地址才显示 -->
            <van-button
              class="default-btn"
              v-if="address.isDefault !== 1"
              @click.stop="setAsDefault(address)"
              :loading="settingDefaultId === address.id"
            >
              设为默认
            </van-button>
            
            <!-- 编辑按钮 -->
            <van-icon 
              name="edit" 
              @click.stop="onEditAddress(address.id)" 
              class="edit-icon"
            />
          </div>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script setup name="Address">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { emitter } from '../utils/eventBus';
import { queryAddresstByUid, setDefaultAddress } from '../api/index';

const router = useRouter();
const addressList = ref([]);
const settingDefaultId = ref(null);

onMounted(async () => {
  emitter.on('addAddress', handleNewAddress);
  emitter.on('updateAddress', handleUpdateAddress);
  emitter.on('refreshAddressList', loadAddressList);
  loadAddressList();
});

//获取最新地址列表
const loadAddressList = async () => {
  try {
    const res = await queryAddresstByUid(1);
    addressList.value = res || [];
  } catch (error) {
    addressList.value = [];
    console.error('获取地址列表失败：', error);
  }
};

// 设为默认地址 
const setAsDefault = async (address) => {
  if (!address.id) return;

  try {
    settingDefaultId.value = address.id;
    await setDefaultAddress(address.id);
    await loadAddressList();
    showToast('设置默认地址成功');
  } catch (error) {
    console.error('设置默认地址失败：', error);
    showToast('设置失败，请重试');
  } finally {
    settingDefaultId.value = null;
  }
};

// 处理新增地址
const handleNewAddress = async (newAddress) => {
  await loadAddressList();
};

// 处理地址更新
const handleUpdateAddress = async (updatedAddress) => {
  await loadAddressList();
};

const onAddAddress = () => {
  router.push('/addressDetail');
};

const onEditAddress = (addressId) => {
  router.push({ path: '/updateAddress', query: { id: addressId } });
};

const onNavBack = () => {
  router.push({name:"checkOrder"})
 // router.go(-1); // 返回上一页，保留页面状态
};

onUnmounted(() => {
  emitter.off('addAddress', handleNewAddress);
  emitter.off('updateAddress', handleUpdateAddress);
  emitter.off('refreshAddressList', loadAddressList);
});
</script>

<style scoped>

.address-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20px;
}

.van-nav-bar {
  background-color: #fff;
}

.address-list {
  margin-top: 10px;
  background-color: #fff;
  padding: 10px 0;
}

.empty-address {
  padding: 50px 20px;
  background-color: #fff;
}

.address-item {
  padding: 15px 12px;
  border-bottom: 1px solid #f5f5f5;
}

.default-tag {
  width: 24px;
  height: 24px;
  background-color: #ffd700;
  color: #fff;
  border-radius: 50%;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.name-phone {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.address-detail {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.default-btn{

     width: 90px;
     height: 40px;
     line-height: 40px;
     font-size: 14px;
     border-radius: 30px;
     background-color: rgb(249, 215, 221);
     font-weight: bold;
     color: rgb(90, 90, 85);


}

.edit-icon {
  font-size: 20px;
  color: #666;
}
</style>
    